<?php
class Recharge{
    protected $main_table = 'data_recharge';
	protected $main_id = 'recharge_id';
	protected $main_id2 = 'recharge_sn';
	protected $db = null;
	protected $type = 'sp';				//充值方 ,sp 与user
	protected $notify_url;
	protected $return_url;

	public function __construct($db,$type='sp'){
		$this->db=$db;
		$this->type = $type;					//充值方
		
	}
   
	public function __destruct(){
		unset($this->db);
	}


 	public function get_table_name() {
	return $this->main_table;
    }
	/**
	* 	insert news
	* 	@param array $data 
	* 	@return int affected count
	*/
	public function insert_data($data){
		if(!is_array($data))
		my_jump('输入的参数有误');
		$row =$this->db->insert($this->main_table, $data);
		return $this->db->getInsertId();
	}
	
	/**
	* 	update news
	* 	@param array $data 
	* 	@param string $where 
	* 	@return int affected count
	*/
	public function update_data($data,$where){
		if(!is_array($data))
		my_jump('输入的参数有误');
		$result = $this->db->update($this->main_table,$data,$where);
		return $result;
	}
	
	
	public function get_data_row($id,$field='*'){
		if(!intval($id))
		my_jump('输入的参数有误!');
		$sql = "SELECT ".$field." FROM ".$this->main_table." WHERE ".$this->main_id."='".intval($id)."' ";
		$data = $this->db->getRow($sql);
		return $data;
	}
	
	public function get_row_by_sn($sn,$field='*'){
		if(!intval($sn))
		my_jump('输入的参数有误!');
		$sql = "SELECT ".$field." FROM ".$this->main_table." WHERE ".$this->main_id2."='".$sn."' ";
		$data = $this->db->getRow($sql);
		return $data;
	}
	

	public function get_data_array($where,$order='recharge_id DESC',$limit='20',$field='*'){
		$sql = "SELECT ".$field." FROM ".$this->main_table." WHERE ".$where." ORDER BY ".$order;
		if(intval($limit)){
			$sql .= " LIMIT ".$limit;
		}
		$data = $this->db->getAll($sql);
		return $data;
	}   

	public function return_verify(){
		require_once(CONFIG_PATH.'alipay_config.php');
		require_once(LIB_PATH.'alipay/alipay_notify.class.php');

		$alipay_notify = new AlipayNotify($alipay_config);
		$verify_result = $alipay_notify->verifyReturn();
	
		if($verify_result) {//验证成功
			
			$out_trade_no = $_GET['out_trade_no'];			//商户订单号
			$trade_no = $_GET['trade_no'];					//支付宝交易号
			$trade_status = $_GET['trade_status'];			//交易状态
		
		
			if($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') {
				//更新订单状态,注意:状态可能在之前的ajax_verify已经提交
				//echo "验证成功<br />";
				return true;
			}
			else {
				return false;
			  //echo "trade_status=".$_GET['trade_status']; 打印结果
			}
			
		}
		else {
			return false;
			//如要调试，请看alipay_notify.php页面的verifyReturn函数
			//echo "验证失败";
		}
	}

	//支付宝,ajax返回信息,在不需要验证或登录的页面内
	public function ajax_verify(){
		require_once(CONFIG_PATH.'alipay_config.php');
		require_once(LIB_PATH.'alipay/alipay_notify.class.php');
		$alipay_notify = new AlipayNotify($alipay_config);
		$verify_result = $alipay_notify->verifyNotify();
		if($verify_result){
			$out_trade_no = $_POST['out_trade_no'];  //支付时提交的商品唯一订单号
			$trade_no = $_POST['trade_no'];				//支付宝系统中的交易流水号
			$trade_status = $_POST['trade_status'];		//结果状态
			if($trade_status=='TRADE_FINISHED' || $trade_status=='TRADE_SUCCESS'){
				return true;
				/*
				订单更新状态 事件记录
				*/	
				//echo "success";		//请不要修改或删除,返回给支付宝
			}else{
				// ajax接收结果失败
				//更新订单状态
			}
		}else{
			return false;
			//echo "fail";			//请不要修改或删除,返回给支付宝
		}
	}

	//支付宝,ajax返回信息,在不需要验证或登录的页面内
	public function mobile_ajax_verify(){
		require_once(CONFIG_PATH.'alipay_config.php');
		require_once(INC_PATH."alipay_function.php");
		
		$notify_data = trim($_POST["notify_data"]);
		//$notify_data = '<notify><partner>2088702043538774</partner><discount>0.00</discount><payment_type>1</payment_type><subject>骨头1</subject><trade_no>2011102716746901</trade_no><buyer_email>4157874@qq.com</buyer_email><gmt_create>2011-10-27 12:10:51</gmt_create><quantity>1</quantity><out_trade_no>1027040323-9215</out_trade_no><seller_id>2088702043538774</seller_id><trade_status>TRADE_FINISHED</trade_status><is_total_fee_adjust>N</is_total_fee_adjust><total_fee>0.01</total_fee><gmt_payment>2011-10-27 12:10:52</gmt_payment><seller_email>17648787@qq.com</seller_email><gmt_close>2011-10-27 12:10:52</gmt_close><price>0.01</price><buyer_id>2088002456173013</buyer_id><use_coupon>N</use_coupon></notify>';

		$verify_data = "notify_data=".$notify_data;  //验证要前缀
		
		$sign =  trim($_POST["sign"]);
		//$sign='HQq7oZ+gvdSDwV4bQh8QO0TdbwG2gEwjtY/fJbZWiuMEBwSG1VBdsQsocfuNALrEEGCFEIDM+bBjFN/idR+zV2CoGuRuofoZP4mEJ28+4p16iapilTr51boBTd2lQmMd8RQjlkNAz6QF6J5soCDH3WjI4pF75U0OqupacF9q7JA=';

		
		//验证签名
		$isVerify = verify($verify_data, $sign);
		
		//如果验签没有通过
		if(!$isVerify){
			$verifytype = $isVerify ? '1' : '0';
			$logdata = date("Y-m-d H:i:s")." data  ".$notify_data ."\nsign  " . $sign." verify ".$verifytype." \n";
			write_file(INFO_PATH.'mlog.log',$logdata,'log');
			
			return false;
			//echo " Verify fail<br>";  //验证失败,并中止
			//echo $verify_data."<br>";
			//dump($verify_data);
			//exit;
		}

		//获取交易状态
		$data = getDataForXML($notify_data, '/notify');
		//$data = object_to_array($xml);
		//dump($data);
		//判断交易是否完成
		if($data['trade_status'] == "TRADE_FINISHED" || $data['trade_status'] == "TRADE_SUCCESS"){
			//echo "success";
			$this->update_mobile_recharge($data);
			return true;
		}
		else{
			return false;
		}

	}

	public function get_alipay_page($info){
		require_once(CONFIG_PATH.'alipay_config.php');
		require_once(LIB_PATH.'alipay/alipay_submit.class.php');
		
		if($this->type=='sp'){				//商家
		    $return_url = $alipay_config['sp_return_url'];			//返回地址
		    $notify_url = $alipay_config['sp_notify_url'];						//ajax返回地址,不能放在需要登录或验证的页面
		}else{						//用户
		    $return_url = $alipay_config['user_return_url'];			//返回地址
			$notify_url = $alipay_config['user_notify_url'];					//ajax返回地址,不能放在需要登录或验证的页面
		    
		}
		
		$setting = array(
					"service" => "create_direct_pay_by_user",					//*接口方式
					"partner" => $alipay_config['partner'],						//*alipay 合作身份者id，以2088开头的16位纯数字
					"payment_type"	=> '1',										//*支付类型
					"notify_url"	=> $notify_url,						//ajax返回通知页面路径 不能加?id=123这类自定义参数 
					"return_url"	=> $return_url,						//页面跳转同步通知页面路径
					"seller_email"	=> $alipay_config['seller'],				//*商家淘宝账号
					"out_trade_no"	=> $info['sn'],								//*商户唯一订单号
					"subject"	=> $info['title'],								//*订单名称
					"total_fee"	=> $info['money'],								//*支付金额
					"body"	=> $info['des'],									//订单描述
					"show_url"	=> '',											//商品展示地址
					"anti_phishing_key"	=> '',									//防钓鱼时间戳,若要使用请调用类文件submit中的query_timestamp函数
					"exter_invoke_ip"	=> '',									//客户端的IP地址,非局域网的外网IP地址，如：221.0.0.1
					"_input_charset"	=>$alipay_config['input_charset']								//编码 utf-8
			);
		
		
		//建立请求
		$alipaySubmit = new AlipaySubmit($alipay_config);
		$html_text = $alipaySubmit->buildRequestForm($setting,"get", "前往支付");
		//echo $html_text;
		return $html_text;

	}
	
	function update_sp_recharge(){
		$out_trade_no = $_REQUEST['out_trade_no'];  //支付时提交的商品唯一订单号
		$trade_no = $_REQUEST['trade_no'];				//支付宝系统中的交易流水号
		$trade_status = $_REQUEST['trade_status'];		//结果状态
		$total_fee = $_REQUEST['total_fee'];			//总费用
		$row = $this->get_row_by_sn($out_trade_no);
	
		if($row){
			switch($row['recharge_status']){
			case "1":  //已支付不处理
				return true;
			break;
			default :							//更新充值单状态
				
				// 1更新充值单状态
				$this->db->begin();
				$sp = new Supplier($this->db);
				$log = new Log($this->db);
				
				if($total_fee==$row['recharge_money']){
					$update = array(
						'recharge_status'=>'1',
						'recharge_alipay_sn'=>$trade_no,
						'recharge_return_time'=>date("Y-m-d H:i:s"),
						'recharge_return_status'=>$trade_status
					);
						
						
					$update2 = array(
						'sp_money'=>"sp_money+".$row['recharge_money'],
					);
					//商家充值
					$rs2 = $sp->update_data($update2,"sp_id='".$row['recharge_uid']."'");
					
					//商家充值记录
					$rs3 = $log->log($row['recharge_money'], $row['recharge_uid'], $row['recharge_user'], 'sp_recharge');
					
					
					//是否返利
										
						
					$sprow = $sp->get_data_row($row['recharge_uid'],"sp_id,sp_name,sp_title,sp_isagent,sp_agent_user,sp_agent_uid,sp_agent_proportion");	
					if($sprow['sp_isagent']){									//是否代理
						$insert = array(
							'rebate_spid' =>$sprow['sp_id'],
							'rebate_sp' =>$sprow['sp_title'] ? $sprow['sp_title'] : $sprow['sp_name'],
							'rebate_from_table' =>'data_recharge',
							'rebate_from_filed' =>'recharge_id',
							'rebate_from_value' =>$row['recharge_id'],
							'rebate_type' =>'user_proxy_recharge',
							'rebate_remark' =>'商家充值订单号:'.$row['recharge_sn'],
							'rebate_from_money' =>$row['recharge_money'],
							'rebate_uid' =>$sprow['sp_agent_uid'],
							'rebate_user' =>$sprow['sp_agent_user'],
							'rebate_rate' =>$sprow['sp_agent_proportion'],
							'rebate_money' =>$row['recharge_money']*$sprow['sp_agent_proportion'],
							'rebate_create_time' =>date("Y-m-d H:i:s"),
							'rebate_status' =>'0',
							
						);
						if($sprow['sp_isagent']=='2'){							//代理商无返利 状态已处理
							$insert['rebate_status'] ='1'; 
							$insert['rebate_isproxy'] ='1'; 
							$update['recharge_rebate'] = '1';
						}else{													//掌友代理,需要处理
							$insert['rebate_status'] ='0';
							$insert['rebate_isproxy'] ='0';
							$update['recharge_rebate'] = '1';
						}
						$rebate = new Rebate($this->db);
						$rs4 = $rebate->insert_data($insert);
							
					}else{
						$rs4 = 1;
					}
					
					$rs1=$this->update_data($update,"recharge_id='".$row['recharge_id']."'");
				
					if($rs1 && $rs2 && $rs3 && $rs4){
						$this->db->commit()	;
						return true;
					}else{
						$this->db->back();	
						return false;
					}
				
				
				}

			break;
			}
		}	
		
	}

	function update_user_recharge(){
		$out_trade_no = $_REQUEST['out_trade_no'];  //支付时提交的商品唯一订单号
		$trade_no = $_REQUEST['trade_no'];				//支付宝系统中的交易流水号
		$trade_status = $_REQUEST['trade_status'];		//结果状态
		$total_fee = $_REQUEST['total_fee'];			//总费用
		$row = $this->get_row_by_sn($out_trade_no);
	
		if($row){
			switch($row['recharge_status']){
			case "1":  //已支付不处理
				return true;
			break;
			default :							//更新充值单状态
				
				// 1更新充值单状态
				$this->db->begin();
				$user = new User($this->db);
				$log = new Log($this->db);
				
				if($total_fee==$row['recharge_money']){
					$update = array(
						'recharge_status'=>'1',
						'recharge_alipay_sn'=>$trade_no,
						'recharge_return_time'=>date("Y-m-d H:i:s"),
						'recharge_return_status'=>$trade_status
					);
					$rs1=$this->update_data($update,"recharge_id='".$row['recharge_id']."'");	
						
					$update2 = array(
						'user_coin'=>"user_coin+".$row['recharge_money'],
					);
					//充值
					$rs2 = $user->update_data($update2,"user_id='".$row['recharge_uid']."'");
					
					//充值记录
					$rs3 = $log->log($row['recharge_money'], $row['recharge_uid'], $row['recharge_user'], 'user_recharge');

					if($rs1 && $rs2 && $rs3){
						$this->db->commit()	;
						return true;
					}else{
						$this->db->back();	
						return false;
					}
				}

			break;
			}
		}	
		
	}

	public function get_recharge_order_data($money,$sn){
		require_once(CONFIG_PATH.'alipay_config.php');
		require_once(INC_PATH.'alipay_function.php');
		
			$subject = "充值掌币";
			$body = "掌友现金充值";
			
			//组装待签名数据
			$signData = "partner=" . "\"" . $alipay_config['partner'] ."\"";
			$signData .= "&";
			$signData .= "seller=" . "\"" .$alipay_config['seller'] . "\"";
			$signData .= "&";
			$signData .= "out_trade_no=" . "\"" . $sn ."\"";
			$signData .= "&";
			$signData .= "subject=" . "\"" . $subject ."\"";
			$signData .= "&";
			$signData .= "body=" . "\"" . $body ."\"";
			$signData .= "&";
			$signData .= "total_fee=" . "\"" . $money ."\"";
			$signData .= "&";
			$signData .= "notify_url=" . "\"" . $alipay_config['mobile_notify_url'] ."\"";
			
			
			//生成签名
			$mysign = sign($signData);
			
			$data = $signData . "&sign=\"" . urlencode($mysign) . "\"&sign_type=" . "\"RSA\"";
			
			return $data;
		
	}
	
	function update_mobile_recharge($data){
		$out_trade_no = $data['out_trade_no'];  //支付时提交的商品唯一订单号
		$trade_no = $data['trade_no'];				//支付宝系统中的交易流水号
		$trade_status = $data['trade_status'];		//结果状态
		$total_fee = $data['total_fee'];			//总费用
		$row = $this->get_row_by_sn($out_trade_no);
	
		if($row){
			switch($row['recharge_status']){
			case "1":  //已支付不处理
				return true;
			break;
			default :							//更新充值单状态
				
				// 1更新充值单状态
				$this->db->begin();
				$user = new User($this->db);
				$log = new Log($this->db);
				
				if($total_fee==$row['recharge_money']){
					$update = array(
						'recharge_status'=>'1',
						'recharge_alipay_sn'=>$trade_no,
						'recharge_return_time'=>date("Y-m-d H:i:s"),
						'recharge_return_status'=>$trade_status
					);
					$rs1=$this->update_data($update,"recharge_id='".$row['recharge_id']."'");	
					
					//$count = $row['recharge_money']*100;
					
					$update2 = array(
						'user_coin'=>"user_coin+".$row['recharge_money'],
					);
					//充值
					$rs2 = $user->update_data($update2,"user_id='".$row['recharge_uid']."'");
					
					//充值记录
					$rs3 = $log->log($row['recharge_money'], $row['recharge_uid'], $row['recharge_user'], 'user_recharge','掌友手机掌币充值');
					
					if($rs1 && $rs2 && $rs3){
						$this->db->commit()	;
						return true;
					}else{
						$this->db->back();	
						$logdata = date("Y-m-d H:i:s")." update_recharge3  money ".$row['recharge_money'] ." recharge_sn " . $out_trade_no. " rs:{$rs} rs2:{$rs2} rs3:{$rs3}"."\n";
						write_file(INFO_PATH.'mlog.log',$logdata,'log');
						return false;
					}
				}	
			break;
			}
		}	
		
	}
		
}
?>